package com.watchme.parser.utils;

import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.text.PDFTextStripper;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

/**
 * Created by wangqiang on 2017/10/26.
 */
public class Pdf2ImgUtil {

    public static boolean parserPdf2Img(String pdfPath, String outImgPath) {
        boolean result = false;
        // 待解析PDF
        File pdfFile = new File(pdfPath);
        String pdfName = pdfFile.getName();
        System.out.println("PDF名称:" + pdfName);
        // 创建目录
        // 如果sPath不以文件分隔符结尾，自动添加文件分隔符
        if (!outImgPath.endsWith(File.separator)) {
            outImgPath = outImgPath + File.separator;
        }
        String dirPath = outImgPath + pdfName;
        FileUtil.createDir(dirPath);
        PDDocument document = null;
        try {
            document = PDDocument.load(pdfFile);
            int pages_size = document.getNumberOfPages();

            System.out.println("PDF总页数:" + pages_size);
            int j = 0;
            String endName = "";
            for (int i = 0; i < pages_size; i++) {
                // 读文本内容
                PDFTextStripper stripper = new PDFTextStripper();
                // 设置按顺序输出
                stripper.setSortByPosition(true);
                stripper.setStartPage(i + 1);
                stripper.setEndPage(i + 1);
                String content = stripper.getText(document);
                content = content.replace(" \r\n", "|"); //一般情况下，\r\n \r\n可以表示一个图片的位置
                content = content.replaceAll(" +", "").replaceAll("\r\n+", "").replaceAll("\\|+","\\|");
                String[] arr = content.split("\\|");
                if (arr.length == 0) {
                    arr = new String[1];
                }
                if (null == arr[0] || "".equals(arr[0])) {
                    arr[0] = "".equals(endName) ? "未知" : endName;
                }
                for (int a = 0; a < arr.length; a++) {
                    if ("".equals(arr[a])) {
                        arr[a] = "未知";
                    }
                }

                endName = arr[arr.length - 1];//为了预防名字在第一页，而图片在第二页的情况

                PDPage page = document.getPage(i);
                PDResources resources = page.getResources();
                Iterable xobjects = resources.getXObjectNames();
                if (xobjects != null) {
                    Iterator imageIter = xobjects.iterator();
                    int count = 0;
                    while (imageIter.hasNext()) {
                        COSName key = (COSName) imageIter.next();
                        if (resources.isImageXObject(key)) {
                            try {
                                // 如果sPath不以文件分隔符结尾，自动添加文件分隔符
                                if (!dirPath.endsWith(File.separator)) {
                                    dirPath = dirPath + File.separator;
                                }

                                PDImageXObject image = (PDImageXObject) resources.getXObject(key);
                                if (count > arr.length) {
                                    count = arr.length - 1;
                                }
                                String imgName = arr[count];

                                //将PDF文档中的图片 分别另存为图片。
                                String filePath = dirPath + "tmp" + j + ".jpg";
                                File file = new File(filePath);
                                BufferedImage input = image.getOpaqueImage();
                                ImageIO.write(input, "jpg", file);
                                System.out.println("文件" + filePath);
                                if ("证件".equals(imgName)) {
                                    System.out.println("特殊处理证件...");
                                    if (ReadColorUtil.getInstance().isChromatic(filePath)) {
                                        //如果证件照是彩色
                                        if (OpenCVUtil.getInstance().isFace(filePath, outImgPath)) {
                                            String oldName = "tmp" + j + ".jpg";
                                            String newName = "身份证正面-" + j + ".jpg";
                                            FileUtil.renameFile(dirPath, oldName, newName);
                                        } else {
                                            String oldName = "tmp" + j + ".jpg";
                                            String newName = "身份证反面-" + j + ".jpg";
                                            FileUtil.renameFile(dirPath, oldName, newName);
                                        }

                                    } else {
                                        String oldName = "tmp" + j + ".jpg";
                                        String newName = "其他证件-" + j + ".jpg";
                                        FileUtil.renameFile(dirPath, oldName, newName);
                                    }

                                } else {
                                    String oldName = "tmp" + j + ".jpg";
                                    String newName = imgName + "-" + j + ".jpg";
                                    FileUtil.renameFile(dirPath, oldName, newName);
                                }


                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            j++;
                            count++;
                        }
                    }
                }
            }

            document.close();
            System.out.println("图片总数量 " + j);

        } catch (IOException e) {
            e.printStackTrace();
            return result;
        }


        return true;
    }
}
